﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Minecraft.WorldMap
{
	internal sealed class StreamFragment : System.IO.Stream
	{
		internal System.IO.Stream BaseStream { get; private set; }
		private long length;
		private long position;
		private long startOffset;
		private static readonly byte[] skipBuffer = new byte[4096];

		internal StreamFragment(System.IO.Stream baseStream, long length)
		{
			BaseStream = baseStream;
			this.length = length;
			this.position = 0;
			if (BaseStream.CanSeek)
				this.startOffset = BaseStream.Position;
			else
				this.startOffset = -1;
#if DEBUG
			if (NamedBinaryTag.DebugFlags.GetDebug(4))
				Console.WriteLine(string.Format("StreamFragment {{ Start = {0}, Length = {1} }}", this.startOffset, this.length));
#endif
		}

		public override bool CanRead
		{
			get { return BaseStream.CanRead; }
		}

		public override bool CanSeek
		{
			get { return BaseStream.CanSeek; }
		}

		public override bool CanWrite
		{
			get { return false; }
		}

		public override void Flush()
		{
			BaseStream.Flush();
		}

		public override long Length
		{
			get { return length; }
		}

		public override long Position
		{
			get
			{
				return position;
			}
			set
			{
				if (!CanSeek)
					throw new NotSupportedException();
				BaseStream.Position = startOffset + Math.Min(Math.Max(value, 0), length);
			}
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			if (position + count > length)
			{
				count = (int)(length - position);
			}
			if (count == 0)
				return 0;
			int read = BaseStream.Read(buffer, offset, count);
			position += read;
			return read;
		}

		public override long Seek(long offset, System.IO.SeekOrigin origin)
		{
			if (origin == System.IO.SeekOrigin.Begin)
				offset += Math.Max(0, startOffset);
			return BaseStream.Seek(offset, origin);
		}

		public override void SetLength(long value)
		{
			throw new NotSupportedException();
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			throw new NotSupportedException();
		}

		internal void SkipToEnd()
		{
			while (Read(skipBuffer, 0, skipBuffer.Length) > 0);
		}
	}
}
